/**
 * DOM utility functions for the Chat吉PT/NODA节点 userscript.
 */

/**
 * Creates a stylesheet with given CSS content and appends it to the document head.
 * @param {string} cssContent - The CSS content to be added to the document.
 */
export function addStyleToHead(cssContent) {
  const style = document.createElement("style");
  const head = document.head || document.getElementsByTagName("head")[0];
  style.appendChild(document.createTextNode(cssContent));
  head.appendChild(style);
}

/**
 * Scrolls an element with the specified ID to the top.
 * @param {HTMLElement} element - The element to scroll to the top.
 */
export function scrollToTop(element) {
  if (element) {
    element.scrollTop = element.scrollHeight;
  }
}

/**
 * Checks if the specified element has focus.
 * @param {HTMLElement} element - The element to check for focus.
 * @returns {boolean} - True if the element has focus, false otherwise.
 */
export function hasFocus(element) {
  return element === document.activeElement;
}

/**
 * 为具有特定类名的元素添加点击复制功能
 * @param {string} className - 要监听的元素的类名
 * @param {Function} [notifyFunc] - 可选的通知函数，用于显示复制成功的消息
 */
export function setupCopyOnClick(className, notifyFunc) {
  // 创建备用通知函数
  const showNotification =
    notifyFunc ||
    function (message) {
      const notification = document.createElement("div");
      notification.textContent = message;
      notification.style.cssText = `
      position: fixed;
      bottom: 20px;
      right: 20px;
      background-color: rgba(40, 42, 54, 0.9);
      color: #f8f8f2;
      padding: 10px 16px;
      border-radius: 6px;
      font-size: 14px;
      z-index: 9999;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
      border-left: 4px solid #6272a4;
      transform: translateY(20px);
      opacity: 0;
      transition: transform 0.3s, opacity 0.3s;
    `;
      document.body.appendChild(notification);

      // 显示通知
      setTimeout(() => {
        notification.style.transform = "translateY(0)";
        notification.style.opacity = "1";
      }, 10);

      // 移除通知
      setTimeout(() => {
        notification.style.transform = "translateY(20px)";
        notification.style.opacity = "0";
        setTimeout(() => {
          if (document.body.contains(notification)) {
            document.body.removeChild(notification);
          }
        }, 300);
      }, 2000);
    };

  // 使用MutationObserver来处理动态添加的元素
  const observer = new MutationObserver((mutations) => {
    // 查找所有具有指定类名的元素
    const elements = document.querySelectorAll(`.${className}`);
    elements.forEach(addCopyListener);
  });

  // 开始观察DOM变化
  observer.observe(document.body, {
    childList: true,
    subtree: true,
  });

  // 初始查找已存在的元素
  const existingElements = document.querySelectorAll(`.${className}`);
  existingElements.forEach(addCopyListener);

  // 添加复制功能到元素
  function addCopyListener(element) {
    // 确保不重复添加事件监听器
    if (element.dataset.hasCopyListener) return;
    element.dataset.hasCopyListener = "true";

    element.style.cursor = "pointer";

    // 添加提示标题
    element.title = "点击复制文本";

    element.addEventListener("click", (event) => {
      // 获取元素的文本内容
      const text = element.textContent;

      // 复制到剪贴板
      navigator.clipboard
        .writeText(text)
        .then(() => {
          // 显示复制成功的临时提示
          const originalTitle = element.title;
          element.title = "已复制!";

          // 添加复制成功动画类
          element.classList.add("copy-success");

          // 显示通知消息
          const displayText =
            text.length > 30 ? text.substring(0, 27) + "..." : text;
          showNotification(`复制成功: ${displayText}`);

          // 一段时间后恢复原样
          setTimeout(() => {
            element.title = originalTitle;
            element.classList.remove("copy-success");
          }, 1000);
        })
        .catch((err) => {
          console.error("复制失败:", err);
          element.title = "复制失败";

          // 显示错误通知
          showNotification("复制失败，请重试");

          // 一段时间后恢复原样
          setTimeout(() => {
            element.title = "点击复制文本";
          }, 1000);
        });
    });
  }
}
